<template>
  <div class="file-con">
    <el-button icon="el-icon-upload"  :loading="isup" >{{txt}}</el-button>
    <input type="file" ref="file" class="file" @change="upFile">
  </div>
</template>

<script>
import {getQiniuToken} from 'api/commonApi'
import * as qiniu from 'qiniu-js'
export default {
  data(){
      return {
        txt: '上传文件',
        isup: false
      }
  },
  methods: {
    upFile(event){
      var files = event.target.files
      files = Array.from(files)
      files.forEach((file) => {
          if(file.size>150*1024*1024){
            alert('上传文件只能为100M内')
          }else{
            getQiniuToken().then(res => {
              let token = res.rData[0].token
              this.fileName = file.name
              this.upload(file, file.name, token)
            })
          }
      })
    },
    progress(res){
      this.isup = true
      this.txt = '正在上传' + (res.total.percent.toFixed(2)) + '%'
    },
    handError(err) {
      console.log(err)
      let message = err.message
      let rex = /response:\s{0,}(\{.*?\})/
      let errmsg = JSON.parse(rex.exec(message)[1]).error
      this.isup = false
      this.txt = '继续上传'
      this.$refs.file.value = ''
      this.$message({
        message: errmsg,
        type: 'error'
      })
    },
    complete(res){
      // 上传文件
      this.$emit('upload-success', res.key, this.fileName)
      this.isup = false
      this.txt = '上传文件'
      this.$refs.file.value = ''
    },
    upload(file, key,token){
      // let putExtra ={
      //   fname: "",
      //   params: {},
      //   mimeType: null
      // }
      // let config = {
      //   useCdnDomain: true,
      //   region: null
      // }
      var observable = qiniu.upload(file, null, token, null, null);
      observable.subscribe({
        next: this.progress,
        error: this.handError, 
        complete: this.complete
      })
    }
  }
}
</script>


<style lang="scss" scoped>
.file-con{
  position: relative;
  cursor: pointer;
  .file{
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0;
  }
}
</style>
